package cn.edu.leetcode.二叉树;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.util.LinkedList;
import java.util.Queue;

@NoArgsConstructor
@AllArgsConstructor
@ToString
public class TreeNode {
    // 基类的 protected 成员是包内可见的，并且对子类可见
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int val) {
        this.val = val;
    }


    public void show() {
        //add()和remove()方法在失败的时候会抛出异常(不推荐)
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(this);

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node == null) {
                System.out.print(null + " ");
            }else {
                System.out.print(node.val + " ");
                queue.offer(node.left);
                queue.offer(node.right);
            }
        }
    }

    public static TreeNode of(int[] a) {
        TreeNode root = null;
        if (a.length == 0) {
            return root;
        }
        root = new TreeNode(a[0]);
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        for (int i = 1; i < a.length; i++) {
            TreeNode node = queue.poll();
            node.left = new TreeNode(a[i++]);
            if (i < a.length) {
                node.right = new TreeNode(a[i]);
                queue.offer(node.left);
                queue.offer(node.right);
            }
        }

        return root;
    }

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1);
        System.out.println(treeNode);
    }
}
